package com.zzyl.nursing.service.impl;

import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.NursingProjectPlan;
import com.zzyl.nursing.dto.NursingPlanDto;
import com.zzyl.nursing.mapper.NursingProjectPlanMapper;
import com.zzyl.nursing.vo.NursingPlanVo;
import com.zzyl.nursing.vo.NursingProjectPlanVo;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.NursingPlanMapper;
import com.zzyl.nursing.domain.NursingPlan;
import com.zzyl.nursing.service.INursingPlanService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;

/**
 * 护理计划Service业务层处理
 *
 * @author ruoyi
 * @date 2025-09-22
 */
@Service
public class NursingPlanServiceImpl extends ServiceImpl<NursingPlanMapper, NursingPlan> implements INursingPlanService {
    @Autowired
    private NursingPlanMapper nursingPlanMapper;
    @Autowired
    private NursingProjectPlanMapper nursingProjectPlanMapper;
    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    /**
     * 查询护理计划
     *
     * @param id 护理计划主键
     * @return 护理计划
     */
    @Override
    public NursingPlanVo selectNursingPlanById(Long id) {
        // 1.根据id查询护理计划
        NursingPlan nursingPlan = nursingPlanMapper.selectNursingPlanById(id);
        NursingPlanVo nursingPlanVo = new NursingPlanVo();
        BeanUtils.copyProperties(nursingPlan, nursingPlanVo);

        // 2.根据护理计划id查询关联的所有护理项目
        List<NursingProjectPlanVo> list = nursingProjectPlanMapper.selectByPlanId(id);
        nursingPlanVo.setProjectPlans(list);
        return nursingPlanVo;

    }

    /**
     * 查询护理计划列表
     *
     * @param nursingPlan 护理计划
     * @return 护理计划
     */
    @Override
    public List<NursingPlan> selectNursingPlanList(NursingPlan nursingPlan) {
        return nursingPlanMapper.selectNursingPlanList(nursingPlan);
    }

    /**
     * 新增护理计划
     *
     * @param nursingPlanDto 护理计划
     * @return 结果
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int insertNursingPlan(NursingPlanDto nursingPlanDto) {

        // 保存护理计划
        NursingPlan nursingPlan = new NursingPlan();
        BeanUtils.copyProperties(nursingPlanDto, nursingPlan);
        nursingPlan.setCreateTime(DateUtils.getNowDate());
        nursingPlanMapper.insertNursingPlan(nursingPlan);

        // 批量保存护理项目计划关系
        int count = nursingProjectPlanMapper.insertBatch(nursingPlanDto.getProjectPlans(), nursingPlan.getId());

        // 删除旧的护理计划缓存
        deleteCache();

        return count == 0 ? 0 : 1;
    }

    /**
     * 修改护理计划
     *
     * @param nursingPlanDto 护理计划
     * @return 结果
     */
    @Override
    public int updateNursingPlan(NursingPlanDto nursingPlanDto) {

        try {
            NursingPlan nursingPlan = new NursingPlan();
            BeanUtils.copyProperties(nursingPlanDto, nursingPlan);

            // 判断nursingPlanDto中的项目列表是否为空，如果不为空，则先删除护理计划和护理项目的关系，然后重新批量添加
            if (nursingPlanDto.getProjectPlans() != null || !nursingPlanDto.getProjectPlans().isEmpty()) {
                // 删除护理计划对应的护理项目列表
                nursingProjectPlanMapper.deleteByPlanId(nursingPlan.getId());
                // 补全护理计划Id
                List<NursingProjectPlan> projectPlans = nursingPlanDto.getProjectPlans();
                projectPlans.forEach(nursingProjectPlan -> nursingProjectPlan.setPlanId(nursingPlan.getId()));
                // 批量保存护理计划对应的护理项目列表
                nursingProjectPlanMapper.insertBatch(projectPlans, nursingPlan.getId());
            }
            // 不管项目列表是否为空，都要修改护理计划
            int flag = nursingPlanMapper.updateNursingPlan(nursingPlan);
            // 删除缓存
            deleteCache();

            return flag;
        } catch (BeansException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 批量删除护理计划
     *
     * @param ids 需要删除的护理计划主键数组
     * @return 删除结果，成功返回1，失败返回0
     */
    @Override
    public int deleteNursingPlanByIds(Long[] ids) {
        // 批量删除护理计划
        boolean flag = removeByIds(Arrays.asList(ids));
        // 删除缓存
        deleteCache();

        return flag ? 1 : 0;
    }


    /**
     * 删除护理计划信息
     *
     * @param id 护理计划主键
     * @return 结果
     */
    @Override
    public int deleteNursingPlanById(Long id) {
        // 删除关联关系
        nursingProjectPlanMapper.deleteByPlanId(id);
        // 删除护理计划
        boolean b = removeById(id);
        // 删除缓存
        deleteCache();

        return b ? 1 : 0;
    }

    /**
     * 获取所有护理计划
     * @return
     */
    @Override
    public List<NursingPlan> getAllNursingPlan() {

        // 先从缓存中查是否有数据
        List<NursingPlan> list = (List<NursingPlan>) redisTemplate.opsForValue().get(CacheConstants.NURSING_PLAN_ALL_KEY);
        // 缓存中有数据，则直接返回
        if(ObjectUtils.isNotEmpty(list)){
            return list;
        }
        // 缓存中没有数据，则从数据库中查询
        LambdaQueryWrapper<NursingPlan> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(NursingPlan::getStatus, 1);
        List<NursingPlan> nursingPlans = nursingPlanMapper.selectList(wrapper);
        // 缓存数据
        redisTemplate.opsForValue().set(CacheConstants.NURSING_PLAN_ALL_KEY, nursingPlans);

        return nursingPlans;
    }

    /**
     * 删除缓存
     */
    private void deleteCache() {
        redisTemplate.delete(CacheConstants.NURSING_PLAN_ALL_KEY);
    }
}
